-- UIManualLearn
-- Created by dengc
-- 工程学手册学习界面

UIManualLearn = class("UIManualLearn", function()
    return cc.Layer:create();
end);

-- 传入奖励列表
function UIManualLearn.create(id)
    return UIManualLearn.new(id);
end

-- 构造函数
function UIManualLearn:ctor(id)
    self:setName("UIManualLearn");
    local node = cc.CSLoader:createNode("layout/common/BonusNotify2.csb");
    self:addChild(node);
    self.node = node;

    self:setLocalZOrder(UIMgr.BONUS_NOTIFY_ZORDER + 1);
    self.CT = findChildByName(self.node, "CT");

    self.id = id;

    -- 注册点击事件
    self:registerTouchEvent();

    -- 重绘
    self:redraw();

    -- 适配
    self:resize();
end

-- 重绘
function UIManualLearn:redraw()
    local id = self.id;

    -- 标题
    local titleLabel = findChildByName(self.CT, "title");
    local title = EngineeringManualM.query(id, "name");
    TextStyleM.setTitleStyle(titleLabel);
    titleLabel:setString(title);

    -- 学习描述
    local descLabel = findChildByName(self.CT, "desc");
    TextStyleM.setTextStyle(descLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN);
    local desc = EngineeringManualM.query(id, "learn_desc") .. "\n";

    -- 大脑注射，心脏注射需要特殊处理下
    if id == 101 or id == 108 then
        local bonusId = EngineeringManualM.query(id, "bonus_id");
        desc = string.gsub(desc, "{num}", FormulaM.invoke("CALC_MANUAL_CURE", EngineeringManualM.queryBonus(bonusId, "lv1")["manual_cure"]));
    end

    -- 对讲机电池需要特殊处理，显示数量
    if id == 501 then
        local num = ItemM.getAmount(ME.user, 7563);
        desc = string.gsub(desc, "{num}", num);
    end

    -- 飞艇能源补给特殊处理
    if id == 507 then
        local data = ME.user.dbase:query("dungeon_sc_data");
        local max_fight_ability = data["max_fight_ability"] or 1;
        local fight_ability = data["fight_ability"] or 0;
        local rate = math.modf(fight_ability / max_fight_ability * 1000);
        desc = string.gsub(desc, "{fight_ability}", fight_ability);
        desc = string.gsub(desc, "{rate}", rate / 10);
    end

    -- 效果描述
    local applyDesc = EngineeringManualM.getBonusDesc(id) or "";
    desc = spliceLocStr(desc, "[blue]" .. applyDesc .. "[-]");

    descLabel = applyString(descLabel, desc);

    -- 图标显示
    local panelNode = findChildByName(self.CT, "bonus_panel");
    local parentNode = findChildByName(panelNode, "bonus_node");
    panelNode:setVisible(true);
    self:redrawIcon(parentNode);

    -- 消耗描述
    local descLabel2 = findChildByName(self.CT, "desc2");
    descLabel2:setVisible(true);
    TextStyleM.setTextStyle(descLabel2, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN);

    -- 如果已经达到最高等级，那么显示其它描述
    local level = EngineeringManualM.getKnowledgeLevel(self.id);
    local maxLevel = EngineeringManualM.query(self.id, "max_level");

    local locStr;
    if level >= maxLevel and EngineeringManualM.query(self.id, "last_id") ~= -1 then
        locStr = getLocStr("engineering_manual_achive_max_level");
    else
        local cost = EngineeringManualM.query(id, "cost");
        locStr = getLocStr("engineering_manual_material_desc" .. sizeof(cost));

        -- 按id排序
        local arr = table.keys(cost);
        table.sort(arr);

        -- 匹配出对应描述
        local index = 1;
        for _, itemId in ipairs(arr) do
            locStr = string.gsub(locStr, "{name" .. index .. "}", ItemM.query(itemId, "name"));

            -- 材料不足显示为红色
            local curNum = ItemM.getAmount(ME.user, itemId);
            if curNum < cost[itemId] then
                locStr = string.gsub(locStr, "{color" .. index .. "}", "[red]");
            else
                locStr = string.gsub(locStr, "{color" .. index .. "}", "[blue]");
            end

            locStr = string.gsub(locStr, "{curNum" .. index .. "}", curNum);
            locStr = string.gsub(locStr, "{needNum" .. index .. "}", cost[itemId]);

            index = index + 1;
        end
    end

    descLabel2 = applyString(descLabel2, locStr);

    -- 重绘确定按钮
    self:redrawBtnOk();

    -- 自适应所有组件
    local bg = findChildByName(self.CT, "bg_frame");
    local okBtn = findChildByName(self.node, "CT/btn_ok");

    local nodeArr = { titleLabel, descLabel, panelNode, descLabel2, okBtn};
    local offsetArr = { 40, 25, 25, 25};

    AlignM.adaptLayout(bg, AlignM.BG_SIZE_SMALL, nodeArr, offsetArr);

    -- 根据适配后的界面高度比例，对界面上的角标位置进行修正
    local bg1 = findChildByName(self.CT, "sub_bg_l");
    local bg2 = findChildByName(self.CT, "sub_bg_r");

    -- 这里要注意一下，原始的模版高度并不是100%，而是85%。。不解
    local fixY, deltaY = math.modf(AlignM.BG_SIZE_SMALL.height * (0.85 - bg:getScaleY()) / 2);

    if fixY > 0 then
        fixY = fixY + 14;
    else
        fixY = fixY + 15;
    end

    bg1:setPositionY(bg1:getPositionY() - fixY);
    bg2:setPositionY(bg2:getPositionY() - fixY);
end

-- 绘制图标
function UIManualLearn:redrawIcon(node)
    -- 先清空
    node:removeAllChildren();

    -- 加载模板
    local item = cc.CSLoader:createNode("layout/equip/equip_item.csb");
    item = replaceNodeWithWidget(item);
    local child = item:clone();
    node:addChild(child);

    child:setScale(0.8);

    -- 背景框
    local bg = findChildByName(child, "bg");
    bg:loadTexture(getFrameBgIconPath("airship_skill"));

    -- icon
    local icon = findChildByName(child, "btn");
    icon:loadTexture(getItemIconPath(EngineeringManualM.query(self.id, "icon")));
    icon:setScale(1.2);

    local offset = EngineeringManualM.query(self.id, "offset");
    icon:setPosition(icon:getPositionX() + offset[1] - 1, icon:getPositionY() + offset[2] + 4);

    -- 能量进度条
    local levelNode = findChildByName(child, "rank");
    local lightStarPath = "images/ui/symbol/energy_little.png";
    local darkStarPath  = "images/ui/symbol/energy_little2.png";
    levelNode:setPosition(levelNode:getPositionX() + 2, levelNode:getPositionY() - 16);

    local level = EngineeringManualM.getKnowledgeLevel(self.id);
    local maxLevel = EngineeringManualM.query(self.id, "max_level");

    local layer = createStarLayerEx(level, maxLevel, lightStarPath, darkStarPath, "center", -0.6);
    if layer then
        levelNode:removeAllChildren();
        levelNode:addChild(layer);
    end
end

-- 重绘确定按钮
function UIManualLearn:redrawBtnOk()
    local id = self.id;

    -- 确定按钮
    local okBtn = findChildByName(self.CT, "btn_ok");
    TextStyleM.setTextStyle(okBtn, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);

    local level = EngineeringManualM.getKnowledgeLevel(id);
    local haveLast = (EngineeringManualM.query(id, "last_id") ~= -1) and not (1 == EngineeringManualM.canIgnoreLast(id));

    local btnText;
    if id == 1   or id == 201 or id == 205 or id == 209 or
       id == 213 or id == 301 or id == 302 or id == 401 or
       id == 405 or id == 409 or id == 413 or id == 501 then
        btnText = getLocStr("manual_learn_text_make");
    elseif id == 101 or id == 108 then
        btnText = getLocStr("manual_learn_text_inject");
    elseif id == 507 then
        btnText = getLocStr("manual_learn_text_recover");
    else
        btnText = getLocStr("manual_learn_text");
    end

    -- 绘制学习按钮
    if level == EngineeringManualM.query(id, "max_level") and haveLast then
        -- 达到最高等级置灰按钮
        okBtn:setBright(false);
        okBtn:setTouchEnabled(false);
    elseif haveLast and not EngineeringManualM.checkCanLearn(id, true) then
        -- 不能学习时，置灰
        okBtn:setBright(false);
        okBtn:setTouchEnabled(false);
    end

    okBtn:setTitleText(btnText);
end

-- 注册点击事件
function UIManualLearn:registerTouchEvent()
    -- 确定按钮点击事件
    local okBtn = findChildByName(self.CT, "btn_ok");
    local function onOkClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_click");

            -- 查询学习条件
            local id = self.id;

            -- 消耗检查
            if not EngineeringManualM.checkCanCost(id) then
                alert(getLocStr("manual_can_not_cost"));
                return;
            end

            -- 等级检查
            if EngineeringManualM.isAchieveMaxLevel(id) then
                alert(getLocStr("manual_level_max"));
                return;
            end

            DungeonActionM.go("study_knowledge", EngineeringManualM.canIgnoreLast(id), id);

            UIMgr.getCurrentScene():removeFormByName("UIManualLearn");
        end
    end
    okBtn:addTouchEventListener(onOkClick);

    -- 注册返回按钮点击事件
    local btNode = findChildByName(self.node, "BT");
    btNode:setVisible(true);

    local btnBack = findChildByName(btNode, "btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 关闭当前界面
            AudioM.playFx("button_return");
            UIMgr.getCurrentScene():removeFormByName("UIManualLearn");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));
end

-- 适配
function UIManualLearn:resize()
    local node = self.node;

    -- bg充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end
